<!--
 * @Author: lilin_:）
 * @version: 1.0
 * @Descripttion: 客户明细
 * @Date: 2021-08-27 09:09:37			
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-03-26 16:27:20
-->
<template>
	<div class="system-user-container">
		<el-card class="box-card">
			<div>
				<div class="my_btn_lay">
					<div class="my_flex my_btn" @click="searchEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--search"></i>
							<span>查找</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="resetEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--refresh"></i>
							<span>重置</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="funnelEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--download"></i>
							<span>导出</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="printTab">
						<div class="my_flex_layout">
							<i class="vxe-icon--print"></i>
							<span>打印</span>
						</div>
					</div>
				</div>

				<vxe-form :data="selectFrom" title-align="left" prevent-submit title-colon>
					<vxe-form-item title="单位名称" field="tiunitNameme" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.tiunitNameme" placeholder="请选择单位名称" @change="change_unitName">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>
					<vxe-form-item title="项目名称" field="type" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" multiple collapse-tags clearable filterable v-model="data.projectID" placeholder="请选择项目名称">
								<el-option v-for="item in selectFrom.projectData" :key="item.id" :label="item.contractName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<!-- <vxe-form-item title="时间" field="contactPerson" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker
								style="width: 100%"
								v-model="data.time"
								type="datetimerange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="YYYY-MM-DD HH:mm:ss"
							>
							</el-date-picker>
						</template>
					</vxe-form-item> -->

					<vxe-form-item title="开始时间" field="time" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time1" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<vxe-form-item title="结束时间" field="time" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time2" type="date" placeholder="结束日期"> </el-date-picker>
						</template>
					</vxe-form-item>

					<!-- <vxe-form-item align="right" span="24" collapse-node>
						<template #default>
							<vxe-button status="primary" content="搜索" @click="searchEvent"></vxe-button>
							<vxe-button content="重置" @click="resetEvent"></vxe-button>
						</template>
					</vxe-form-item> -->
				</vxe-form>
			</div>
			<!-- 
			<vxe-toolbar ref="xToolbar" custom>
				<template #buttons> </template>
				<template #tools>
					<vxe-button type="text" icon="vxe-icon--print" class="tool-btn" @click="printTab"></vxe-button>
					<vxe-button type="text" icon="vxe-icon--download" class="tool-btn" @click="funnelEvent"></vxe-button>
				</template>
			</vxe-toolbar> -->

			<!-- @edit-closed="editClosedEvent" -->
			<!-- :edit-config="{ trigger: 'click', mode: 'row' }" -->
			<vxe-table
				:scroll-x="{ enabled: false }"
				:scroll-y="{ enabled: false }"
				class="mytable-style"
				border
				keep-source
				:height="770"
				align="center"
				ref="xTable1"
				:export-config="{}"
				resizable
				show-overflow
				:data="tableData"
				@checkbox-all="selectAllChangeEvent1"
				@checkbox-change="selectChangeEvent1"
			>
				<!-- <vxe-column type="checkbox" width="60"></vxe-column> -->
				<vxe-column type="seq" title="序号" width="60"></vxe-column>

				<vxe-column field="timeStr" title="时间" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="unitName" title="单位名称" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="contractName" title="项目名称" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="billMoney" title="开票金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.billMoney) }}</template>
				</vxe-column>
				<vxe-column field="receivePayment" title="收款金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.receivePayment) }}</template>
				</vxe-column>
				<vxe-column field="paymentAmount" title="付款金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.paymentAmount) }}</template>
				</vxe-column>
			</vxe-table>
		</el-card>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, toRaw, onMounted, nextTick } from 'vue';

import { ElMessage, ElMessageBox } from 'element-plus';
import { axios_SelList } from '/@/api/basicsUrl/index';
import { axios_contactsAdd } from '/@/api/addressBook/index';
import { axios_getClientSelList_user, axios_selListByContractUnitId } from '/@/api/customerDetails/index';
import { transitionNumber } from '/@/utils/transitionNumber';

export default {
	name: 'CustomerDetails',
	setup() {
		const xTable1 = ref({} as VxeTableInstance);
		const xToolbar = ref({} as VxeToolbarInstance);

		// 打印样式
		// 打印样式
		const printStyle = `
            .title {
              text-align: center;
            }
            .my-list-row {
              display: inline-block;
              width: 100%;
            }
            .my-list-col {
              float: left;
              width: 33.33%;
              height: 28px;
              line-height: 28px;
            }
            .my-top,
            .my-bottom {
              font-size: 12px;
            }
            .my-top {
              margin-bottom: 5px;
            }
            .my-bottom {
              margin-top: 30px;
              text-align: right;
            }
            `;

		// 打印顶部内容模板
		const topHtml = `
            <h1 class="title">出货单据</h1>
            <div class="my-top">
              <div class="my-list-row">
                <div class="my-list-col">商品名称： </div>
                <div class="my-list-col">发货单号：X2665847132654</div>
                <div class="my-list-col">发货日期：2020-09-20</div>
              </div>
              <div class="my-list-row">
                <div class="my-list-col">收货姓名： </div>
                <div class="my-list-col">收货地址：火星第七区18号001</div>
                <div class="my-list-col">联系电话：10086</div>
              </div>
            </div>
            `;

		// 打印底部内容模板
		const bottomHtml = `
            <div class="my-bottom">
              <div class="my-list-row">
                <div class="my-list-col"></div>
                <div class="my-list-col">创建人： </div>
                <div class="my-list-col">创建日期：2020-09-20</div>
              </div>
            </div>
            `;

		const state: any = reactive({
			selectFrom: {
				unitName: '', //单位名称
				tiunitNameme: '', //单位名称穿ID
				// time: '', //时间搜索
				on: 0, //默认是0，1是点击
				time1: '', //时间
				time2: '', //结束时间

				// type: '', //单位类型1供应商2客户3公司员工
				// typeArry: [
				// 	{ label: '供应商', value: '1' },
				// 	{ label: '客户', value: '2' },
				// 	{ label: '公司员工', value: '3' },
				// ], //单位类型1供应商2客户3公司员工
				unitsData: [], //单位搜索的数据和联系人一样
				projectData: [], //项目数据
				projectID: [], //项目id
			},
			tableData: [], //表格数据
		});

		const selectAllChangeEvent1: VxeTableEvents.CheckboxAll = ({ checked, records }: any) => {
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
		};

		const selectChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked, records }: any) => {
			console.log(checked ? '勾选事件' : '取消事件', records);
		};

		/**
		 * @Author: lilin_:）
		 * @name: 获取单位名称
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getClientSelList = async () => {
			let resData: any = await axios_SelList({ unitName: '', contactPerson: '', type: '2' });
			state.selectFrom.unitsData = resData.obj;
		};

		/**
		 * @Author: lilin_:）
		 * @name:
		 * @Descripttion: 搜索
		 * @param {*}
		 * @return {*}
		 */
		const searchEvent: VxeFormEvents.Submit = async () => {
			// VXETable.modal.message({ content: '查询事件', status: 'info' });
			state.selectFrom.on = 1; // //默认是0，1是点击
			await getClientSelList_user();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 重置搜索表单
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const resetEvent: VxeFormEvents.Reset = async () => {
			state.selectFrom.tiunitNameme = ''; //单位名称
			state.selectFrom.time2 = ''; //搜索时间
			state.selectFrom.projectData = []; //项目数据
			state.selectFrom.on = 0; // //默认是0，1是点击
			state.selectFrom.time1 = ''; //  搜索时间

			await getClientSelList_user();
			// VXETable.modal.message({ content: '重置事件', status: 'info' });
		};

		onMounted(() => {
			getClientSelList(); //单位名称
			getClientSelList_user();

			// let a = GenNonDuplicateID()
			// console.log(a)
		});

		//实时更新
		const editClosedEvent: VxeTableEvents.EditClosed = ({ row, column }) => {
			console.log(toRaw(column), '11111');
			let getRow: any = row;

			// console.log(toRaw(getRow, '111111111'));
			axios_contactsAdd(getRow).then((res) => {
				// console.log(res, '111111111');
				if (res.code == 200) {
					ElMessage.success({
						message: `${res.msg}`,
						type: 'success',
					});
				}
			});

			const $table = xTable1.value;
			const field = column.property;
			const cellValue = row[field];
			// 判断单元格值是否被修改;
			// if ($table.isUpdateByRow(row, field)) {
			// 	setTimeout(() => {
			// 		VXETable.modal.message({
			// 			content: `局部保存成功！ ${field}=${cellValue}`,
			// 			status: 'success',
			// 		});
			// 		// 局部更新单元格为已保存状态
			// 		$table.reloadRow(row, null, field);
			// 	}, 300);
			// }
		};

		/**
		 * @Author: lilin_:）
		 * @name: 关联表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = xTable1.value;
			const $toolbar = xToolbar.value;
			$table.connect($toolbar);
		});

		/**
		 * @Author: lilin_:）
		 * @name: 新增空白行
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const addDefaultBlank = () => {
			let addArry = defaultBlankData.map((item: any) => {
				return {
					...item,
					...{
						webid: GenNonDuplicateID(),
					},
				};
			});
			state.invoiceLedgerTableData = JSON.parse(JSON.stringify([...state.invoiceLedgerTableData, ...addArry]));
			console.log(toRaw(state.invoiceLedgerTableData), '11111111111');
			ElMessage.success({
				message: '新增1行空白栏',
				type: 'success',
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 删除数据
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const deleteTable: any = async () => {
			let webAddArry: any = [];
			let reeData: any = [];
			state.selectData.forEach((item: any) => {
				if (item.iswebAdd == true) {
					webAddArry.push(item);
				} else {
					reeData.push(item);
				}
			});
			// 判断前端数据是否有值
			let webDelet = () => {
				if (webAddArry.length != 0) {
					// 前端删除
					state.invoiceLedgerTableData = state.invoiceLedgerTableData.filter((item: any) => {
						return !webAddArry.find((_item: any) => _item.webid === item.webid);
					});
					// 删除方法2
					// 		state.invoiceLedgerTableData=arr;
					// 	const arr=state.invoiceLedgerTableData;
					// 		console.log(JSON.parse(JSON.stringify(arr)),'aaaaaaaaaaaaaaaaaaaaa');
					// webAddArry.forEach((item:any) => {
					// 			arr.forEach((_item,_index) => {
					// 					if(_item.webid===item.webid){
					// 							arr.splice(_index,1)
					// 					}
					// 			});
					// });
					// state.invoiceLedgerTableData=JSON.parse(JSON.stringify(arr))
				}
			};

			let resDelet = async () => {
				if (reeData.length != 0) {
					let { code }: object = await axios_billDell(
						reeData.map((item: any) => {
							return item.id;
						})
					);

					// console.log(code, '11111111');
					if (code == 200) {
						getInvoiceLedgerTableData();
					}
				}
			};
			await resDelet();
			await webDelet();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 高级导出功能
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const funnelEvent = () => {
			const $table = xTable1.value;
			$table.openExport();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 打印表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const printTab = () => {
			const $table = xTable1.value;
			$table.print({
				sheetName: '客户明细',
				style: printStyle, //自定义样式
				columns: [
					{ type: 'id' },
					{ field: 'timeStr' },
					{ field: 'unitName' },
					{ field: 'contractName' },
					{ field: 'billMoney' },
					{ field: 'receivePayment' },
					{ field: 'paymentAmount' },
				],
				beforePrintMethod: ({ content }) => {
					// 拦截打印之前，返回自定义的 html 内容
					// return topHtml + content + bottomHtml;
					return content;
				},
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 获取客户明细表
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getClientSelList_user = async () => {
			// console.log( toRaw(state.selectFrom.projectID) ,'projectID')
			// let sendTime = '';
			// if (state.selectFrom.time) {
			// 	sendTime = `${state.selectFrom.time[0]}_${state.selectFrom.time[1]}`;
			// }

			let { code, obj } = await axios_getClientSelList_user(
				{
					contractUnitId: state.selectFrom.tiunitNameme,
					// contractUnitId: 10,
					time1: state.selectFrom.time1, //开始时间
					time2: state.selectFrom.time2, //结束
					on: state.selectFrom.on, // //默认是0，1是点击
					// time: sendTime,
					// time: ``,
				},
				state.selectFrom.projectID
			);
			if (code == 200) {
				state.tableData = obj;
			}
		};

		/**
		 * @Author: lilin_:）
		 * @name:
		 * @Descripttion:切换单位名称事件
		 * @param {*} value
		 * @return {*}
		 */
		const change_unitName = async (value: any) => {
			console.log(value, 'value我是拿到的');
			await get_selListByContractUnitId(value);
		};

		/**
		 * @Author: lilin_:）
		 * @name: 通过单位名称查询项目名称
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const get_selListByContractUnitId = async (id: any) => {
			let { obj } = await axios_selListByContractUnitId({
				contractUnitId: id,
			});
			state.selectFrom.projectID = [];
			state.selectFrom.projectData = obj;

			// console.log(obj, '11111111111111111111');
		};

		return {
			...toRefs(state),
			editClosedEvent, //实时更新
			xToolbar, //关联表格
			xTable1, //表格
			addDefaultBlank, //新增空白行
			deleteTable, //删除数据
			funnelEvent, //导出数据
			printTab, //打印
			change_unitName, //切换单位名称
			getClientSelList,

			selectAllChangeEvent1,
			selectChangeEvent1,

			searchEvent,
			resetEvent,
			transitionNumber,
		};
	},
};
</script>

<style scoped lang="scss"></style>
